import java.lang.reflect.Constructor;

/**
 * @author 黄军艳
 * @version 1.0
 * @date 2024/11/22  10:48
 */
public class AccessPersonConstructors {
    public static void main(String[] args) {
        try {
            Class clz=Class.forName("reflect.entity.Person");
            Object obj=clz.newInstance();
            //获取Person的无参构造，public Person()
            Constructor c1=clz.getDeclaredConstructor();
            //Person的无参构造为public，这里可以直接访问
            obj=c1.newInstance();
            System.out.println(obj);

            //获取Person的单参构造 ：private Person(Strinng)
            Constructor c2=clz.getDeclaredConstructor(String.class);
            c2.setAccessible(true);
            obj=c2.newInstance("New Person");
            System.out.println(obj);

            //获取Person的三参构造
            Constructor c3=clz.getDeclaredConstructor(String.class,String.class,String.class);
            c3.setAccessible(true);
            obj=c3.newInstance("New Person","beijing","Hello!");
            System.out.println(obj);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
